import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/layout'
import storage from '@/utils/storage'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

Vue.use(VueRouter)

// 解决路由自己跳自己的警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

// 1. 写死的
const constRoutes = [
  { path: '/login', component: () => import('@/views/login') },
  // 后台首页
  {
    path: '/',
    component: Layout,
    redirect: '/Home',
    meta: { title: '后台首页' },
    children: [{ path: '/Home', component: () => import('@/views/home') }]
  }
]

// 动态路由

// 2. 动态计算的
const dyanamicRoutes = [
  // 订单管理
  {
    path: '/',
    component: Layout,
    redirect: '/Order',
    meta: {
      title: '订单管理',
      roles: ['super'],
      icon: 'icon-order'
    },
    children: [
      {
        path: '/Order',
        component: () => import('@/views/order/OrderList.vue'),
        meta: { roles: ['super'] }
      },
      {
        path: '/Order/OrderEdit',
        component: () => import('@/views/order/OrderEdit.vue'),
        meta: { roles: ['super'] }
      }
    ]
  },

  // 商品管理
  {
    path: '/goods',
    component: Layout,
    redirect: '/goods/GoodsList',
    meta: {
      title: '商品管理',
      roles: ['super', 'normal'],
      icon: 'icon-goods'
    },
    children: [
      {
        path: '/goods/GoodsList',
        meta: { title: '商品列表', roles: ['super', 'normal'] },
        component: () => import('@/views/goods/GoodsList.vue')
      },
      {
        path: '/goods/GoodsAdd',
        meta: { title: '商品添加', roles: ['super', 'normal'] },
        component: () => import('@/views/goods/GoodsAdd.vue')
      },
      {
        path: '/goods/GoodsCategory',
        meta: { title: '商品分类', roles: ['super'] },
        component: () => import('@/views/goods/GoodsCategory.vue')
      }
    ]
  },

  // 店铺管理
  {
    path: '/Shop',
    component: Layout,
    redirect: '/Shop',
    meta: {
      title: '店铺管理',
      roles: ['super', 'normal'],
      icon: 'icon-shop'
    },
    children: [
      {
        path: '/Shop',
        component: () => import('@/views/shops/index.vue'),
        meta: {
          roles: ['super', 'normal']
        }
      }
    ]
  },

  // 账号管理
  {
    path: '/account',
    component: Layout,
    redirect: '/account/AccountList',
    meta: {
      title: '账号管理',
      roles: ['super', 'normal'],
      icon: 'icon-account'
    },
    children: [
      {
        path: '/account/AccountList',
        meta: { title: '账号列表', roles: ['super'] },
        component: () => import('@/views/account/AccountList.vue')
      },
      {
        path: '/account/AccountAdd',
        meta: { title: '添加账号', roles: ['super'] },
        component: () => import('@/views/account/AccountAdd.vue')
      },
      {
        path: '/account/PasswordModify',
        meta: { title: '修改密码', roles: ['super', 'normal'] },
        component: () => import('@/views/account/PasswordModify.vue')
      },
      {
        path: '/account/Personal',
        meta: { title: '个人中心', roles: ['super', 'normal'] },
        component: () => import('@/views/account/Personal.vue')
      }
    ]
  }
]

// console.log(dyanamicRoutes)
const router = new VueRouter({
  routes: constRoutes
})

// 白名单
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  NProgress.start()
  // 1. 判断是否已经登录 token
  if (storage.getItem('token')) {
    // 2. 判断是否是登录页面,如果是跳转到首页
    if (to.path === '/login') {
      next('/home')
    } else {
      next()
    }
  } else {
    // 没有token，但是属于白名单中的直接放行
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      // 如果没有token，并且在白名单中的页面，跳转到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

// function hasRole(route, role) {
//   return route.meta && route.meta.roles && route.meta.roles.includes(role)
// }

// function recursionRoutes(routes, role) {
//   return routes.filter((item) => {
//     if (hasRole(item, role)) {
//       if (item.children && item.children.length) {
//         item.children = recursionRoutes(item.children, role)
//       } else {
//         return item
//       }
//     }
//   })
// }

/* 计算路由 */
export const calcRoutes = () => {
  const role = storage.getItem('role') // 获取出当前用户角色
  if (!role) return // 取不到 直接return  不走后面代码

  // 根据当前role 和 动态路由 算出当前角色能访问哪些路由
  const r = dyanamicRoutes.filter((v) => {
    return v.meta && v.meta.roles && v.meta.roles.includes(role)
  })

  r.forEach((v) => {
    if (v.children && v.children.length) {
      v.children = v.children.filter((item) => {
        return item.meta && item.meta.roles && item.meta.roles.includes(role)
      })
    }
  })
  // 递归计算
  // const r = recursionRoutes(dyanamicRoutes, role)

  // 这个r就是算出来的当前角色可以访问的路由
  router.addRoutes(r) // 把算出来的路由 增加进入配置中

  // 存入本地,方便之后设置权限菜单
  storage.setItem('routes', [
    {
      path: '/',
      component: Layout,
      redirect: '/Home',
      meta: { title: '后台首页', icon: 'icon-home' },
      children: [
        { path: '/Home', component: () => import('@/views/home/index.vue') }
      ]
    },
    ...r
  ])
}
calcRoutes()
export default router
